package com.cans.lightning.business.core.service;

import com.cans.lightning.business.core.constant.Constants;
import com.cans.lightning.business.pms.dto.SysUserDto;
import com.cans.lightning.config.redis.RedisCache;
import com.cans.lightning.utils.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author shencan
 * @date 2020/8/22 12:17
 */
@Component
public class TokenService {

    /**
     * 令牌自定义标识
     */
    @Value("${token.header}")
    private String header;

    /**
     * 令牌秘钥
     */
    @Value("${token.secret}")
    private String secret;

    /**
     * 令牌有效期（默认30分钟）
     */
    @Value("${token.expireTime}")
    private int expireTime;


    protected static final long MILLIS_MINUTE = 60;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60L;

    @Resource
    private RedisCache redisCache;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public SysUserDto getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        Claims claims = parseToken(token);
        // 解析对应的权限以及用户信息
        String userId = (String) claims.get(Constants.LOGIN_USER_KEY);
        String userKey = getTokenKey(userId);
        return redisCache.getCacheObject(userKey);

    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(SysUserDto userDto) {
        if (StringUtils.isNotNull(userDto)) {
            refreshToken(userDto);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String userId) {
        if (StringUtils.isNotEmpty(userId)) {
            String userKey = getTokenKey(userId);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param userDto 用户信息
     * @return 令牌
     */
    public String createToken(SysUserDto userDto) {
        refreshToken(userDto);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, userDto.getId());

        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param userDto
     * @return 令牌
     */
    public void verifyToken(SysUserDto userDto) {

        LocalDateTime expireTime = userDto.getExpireTime();

        long expireSecond = expireTime.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();

        long epochSecond = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();

        if (expireSecond - epochSecond <= MILLIS_MINUTE_TEN) {
            refreshToken(userDto);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param userDto 登录信息
     */
    public void refreshToken(SysUserDto userDto) {
        userDto.setLoginTime(LocalDateTime.now());
        userDto.setExpireTime(userDto.getLoginTime().plusMinutes(expireTime));
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(userDto.getId());

        redisCache.setCacheObject(userKey, userDto, expireTime, TimeUnit.MINUTES);
    }


    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {

        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String userId) {
        return Constants.LOGIN_TOKEN_KEY + userId;
    }
}
